import { mySessionStorage } from '@/utils/storage';
import { Line, Pie } from '@ant-design/plots';
import { Grid, List } from 'antd-mobile';
import { DownOutline, RightOutline, UpOutline } from 'antd-mobile-icons';
import { useEffect, useState } from 'react';
import { history } from 'umi';

export default function MChart({ data, type, startTime, endTime }: any) {
  const { classification, rank, sumMoney, budget, expendSumMoney } = data;
  const typeTitle: string = type === 1 ? '收入' : '支出';

  const [expendFlag, setExpendFlag] = useState<boolean>(false);
  const [showMore, setShowMore] = useState<boolean>(false);
  const [classificationArr, setClassificationArr] = useState<any[]>([]);
  let transactionConfig: { key: number; value: string }[] = [];
  if (mySessionStorage('get', 'transactionConfig')) {
    transactionConfig = mySessionStorage('get', 'transactionConfig') as {
      key: number;
      value: string;
    }[];
  }

  const getTransaction = (key: number) => {
    if (transactionConfig) {
      const configItem = transactionConfig.find((item) => item.key === key);
      return configItem?.value || null;
    }
  };
  useEffect(() => {
    setShowMore(false);
    if (rank && rank.length >= 5) {
      setShowMore(true);
    }
  }, [rank]);
  useEffect(() => {
    if (classification) {
      if (expendFlag) {
        setClassificationArr(classification);
      } else {
        setClassificationArr(classification.slice(0, 5));
      }
    }
  }, [classification, expendFlag]);
  const config = {
    data: data ? data.trend : [],
    xField: 'payDay',
    yField: 'money',
    autoFit: true,
    // seriesField: 'year',
    xAxis: {
      type: 'time',
      // 设置X轴刻度标签数量为5
      tickCount: 5,
      // 或者设置间隔显示，每n个显示一个
      // 如果需要自定义间隔策略，也可以使用回调函数
      // interval: (index, count) => index % (Math.ceil(count / 5)) === 0,
    },
    point: {
      shapeField: 'square',
      // sizeField: 4,
    },
    interaction: {
      tooltip: {
        marker: false,
      },
    },
    // style: {
    //   lineWidth: 2,
    // },
    height: 300,
  };
  const config2 = {
    data: data ? data.classification : [],
    angleField: 'money',
    colorField: 'transactionType',
    radius: 0.8,
    label: {
      text: (d) => `${getTransaction(d.transactionType)}\n ${d.money}`,
      position: 'outside',
      layout: [
        { type: 'interval-hide-overlap' }, // 自动隐藏重叠标签
      ]
    },
    height: 400,
    legend: false,
  };
  return (
    <div>
      <Grid columns={2}>
        <Grid.Item>
          <h3 style={{ fontWeight: 'bold', paddingTop: '0.5rem' }}>
            {typeTitle}
          </h3>
          <div style={{ fontSize: '1.5rem', padding: '0.5rem 0' }}>{`￥ ${sumMoney}`}</div>
        </Grid.Item>
        <Grid.Item>
          <h3 style={{ fontWeight: 'bold', paddingTop: '0.5rem' }}>剩余预算</h3>
          <div style={{ fontSize: '1.5rem', padding: '0.5rem 0' }}>{`￥ ${(budget - expendSumMoney).toFixed(2)}`}</div>
        </Grid.Item>
      </Grid>
      <h3 style={{ fontWeight: 'bold', padding: '30px 0' }}>{typeTitle}趋势</h3>
      <Line {...config} />
      <h3 style={{ fontWeight: 'bold', padding: '30px 0' }}>分类{typeTitle}排行榜</h3>
      <Pie {...config2} />
      <List>
        {classificationArr
          ? classificationArr.map((item, index) => (
            <List.Item key={index} onClick={() => {
              history.push(`/transactionTypeList?startTime=${startTime}&endTime=${endTime}&transactionType=${item.transactionType}&type=${type}`);
            }}>
              <Grid columns={8} style={{ fontSize: '0.9rem' }}>
                <Grid.Item>{index + 1}</Grid.Item>
                <Grid.Item span={5}>
                  <span style={{ fontWeight: 'bold' }}>
                    {getTransaction(item.transactionType)}
                  </span>
                  <span
                    style={{
                      paddingLeft: '1rem',
                      fontSize: '0.8rem',
                      color: '#bbb',
                    }}
                  >
                    {item.count}笔
                  </span>
                </Grid.Item>
                <Grid.Item
                  style={{ fontWeight: 'bold', textAlign: 'right' }}
                  span={2}
                >
                  {item.money}
                </Grid.Item>
              </Grid>
            </List.Item>
          ))
          : null}
      </List>
      {classification && classification.length >= 5 ? (expendFlag ? (
        <div
          style={{ color: '#bbb', textAlign: 'center', paddingTop: '1rem' }}
          onClick={(e) => {
            e.stopPropagation();
            setExpendFlag(false);
          }}
        >
          收起
          <UpOutline style={{ marginLeft: '0.5rem' }} />
        </div>
      ) : (
        <div
          style={{ color: '#bbb', textAlign: 'center', paddingTop: '1rem' }}
          onClick={(e) => {
            e.stopPropagation();
            setExpendFlag(true);

          }}
        >
          展开全部
          <DownOutline style={{ marginLeft: '0.5rem' }} />
        </div>
      )) : null}

      <h3 style={{ fontWeight: 'bold', padding: '30px 0' }}>{typeTitle}排行</h3>
      {rank &&
        rank.slice(0, 3).map((item, index) => (
          <List key={index}>
            <List.Item onClick={() => {
              history.push(`/rankDetail?data=${JSON.stringify(rank)}&startTime=${startTime}&endTime=${endTime}&type=${type}`);
            }}>
              <Grid columns={8} style={{ fontSize: '0.9rem' }}>
                <Grid.Item style={{ display: 'flex', alignItems: 'center' }}>
                  {index + 1}
                </Grid.Item>
                <Grid.Item span={5}>
                  <div
                    style={{
                      fontWeight: 'bold',
                      overflow: 'hidden',
                      whiteSpace: 'nowrap',
                      textOverflow: 'ellipsis',
                    }}
                  >
                    {item.notes}
                  </div>
                  <div
                    style={{
                      fontSize: '0.8rem',
                      color: '#bbb',
                      overflow: 'hidden',
                      whiteSpace: 'nowrap',
                      textOverflow: 'ellipsis',
                    }}
                  >
                    {getTransaction(item.transactionType)}
                  </div>
                </Grid.Item>
                <Grid.Item
                  style={{
                    fontWeight: 'bold',
                    justifyContent: 'flex-end',
                    display: 'flex',
                    alignItems: 'center',
                  }}
                  span={2}
                >
                  {item.money} <RightOutline style={{ color: '#bbb' }} />
                </Grid.Item>
              </Grid>
            </List.Item>
          </List>
        ))}
      {
        showMore ? <div style={{ color: '#bbb', textAlign: 'center', paddingTop: '1rem' }} onClick={() => {
          console.log(rank);
          history.push(`/rankDetail?data=${JSON.stringify(rank)}&startTime=${startTime}&endTime=${endTime}&type=${type}`);
        }}>
          查看更多
          <DownOutline style={{ marginLeft: '0.5rem' }} />
        </div> : null
      }

    </div>
  );
}
